<?php

namespace app\admin\controller\api;

use app\common\model\ClassDay;
use app\common\model\CourseDetail;
use app\common\model\Teach;

/**
 * 班级
 * @internal
 */
class Classes extends Api
{
    protected $noNeedLogin = ['profile', 'course', 'getClassNameByIds', 'todayCourse', 'faces', 'students', 'teachers', 'schoolTeachers', 'currentCourseAttendance'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 班级列表
     *
     * @param school_id int 学校id
     * @param class_ids string 班级ids
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $school_id = $this->request->request('school_id');

        // 班级ids 这里不是要根据班级id取值 只是为了确认是否被选中
        $class_ids = $this->request->request('class_ids');
        if (!is_array($class_ids)) {
            $class_ids = explode(',', $class_ids);
        }

        $classes = \app\common\model\Classes::alias('classes')
            ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
            ->where('classes.school_id', $school_id)
            ->field('classes.id,classes.name,grade.id grade_id,grade.name grade_name')
            ->order('classes.id', 'asc')
            ->select();

        $data = [];
        foreach ($classes as $key => $class) {

            $data[$class['grade_id']]['id'] = $class['grade_id'];
            $data[$class['grade_id']]['title'] = $class['grade_name'];
            $data[$class['grade_id']]['last'] = false;
            $data[$class['grade_id']]['parentId'] = '0';
            $data[$class['grade_id']]['checkArr'] = '1';

            $checkArr = "0";
            if (in_array($class['id'], $class_ids)) {
                $checkArr = "1";
            } else {
                $data[$class['grade_id']]['checkArr'] = "0";
            }

            $data[$class['grade_id']]['children'][] = [
                "id" => $class['grade_id'] . $class['id'],
                "basicData" => $class['id'],
                "title" => $class['name'],
                "last" => true,
                "parentId" => $class['grade_id'],
                "checkArr" => $checkArr,
            ];
        }

        $this->success('', array_values($data));
    }

    /**
     * 班级信息
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function profile()
    {
        $class_id = $this->request->request('class_id');

        $classes = \app\common\model\Classes::alias('classes')
            ->join('__SCHOOL__ school', 'school.id = classes.school_id')
            ->join('__AREA__ area', 'area.id = school.city_id')
            ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
            ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
            ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
            ->join('__GARDEN__ garden', 'garden.id = building.garden_id', 'left')
            ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->field('classes.id,classes.name,classes.logo,classes.slogan,classes.grade_id,grade.name grade_name,classes.school_id,school.name school_name,school.logo school_logo,classes.classroom_id,classroom.name classroom_name,building.id building_id,building.name building_name,garden.id garden_id,garden.name garden_name,classes.headmaster,user.nickname headmaster_name,user.avatar headmaster_avatar,area.shortname city_name')
            ->where('classes.id', $class_id)
            ->find();

        if ($classes) {
            $classes->student_num = \app\common\model\ClassStudent::where('class_id', $class_id)->count();
            $classes->teacher_num = Teach::where('FIND_IN_SET(:class_id, class_ids)', ['class_id' => $class_id])->group('teacher_id')->count();
            if (!$classes->logo) {
                $classes->logo = config('app_url') . '/assets/images/class_default_logo.png';
            }
            if (!strstr($classes->school_logo, 'http') && strstr($classes->school_logo, 'uploads/')) {
                $classes->school_logo = config('app_url') . $classes->school_logo;
            }
            if (!strstr($classes->headmaster_avatar, 'http') && strstr($classes->headmaster_avatar, 'uploads/')) {
                $classes->headmaster_avatar = config('app_url') . $classes->headmaster_avatar;
            }
        }

        $this->success('', $classes);
    }

    public function profiles()
    {
        $class_ids = $this->request->request('ids/a');
        $classes = \app\common\model\Classes::alias('classes')
            ->join('__SCHOOL__ school', 'school.id = classes.school_id')
            ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
            ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->whereIn('classes.id', $class_ids)
            ->column('classes.id,classes.name,classes.logo,classes.grade_id,grade.name grade_name,classes.school_id,school.name school_name,classes.headmaster,user.nickname headmaster_name,user.avatar headmaster_avatar', 'classes.id');

        foreach ($classes as $key => $class) {
            if (!$class['logo']) {
                $class['logo'] = config('app_url') . '/assets/images/class_default_logo.png';
            }
            if (!strstr($class['logo'], 'http') && strstr($class['logo'], 'uploads/')) {
                $class['logo'] = config('app_url') . $class['logo'];
            }
        }

        $this->success('', $classes);

    }

    /**
     * 根据id获取名称
     */
    public function getNameById()
    {
        $class_ids = $this->request->request('class_ids/a');
        $list = \app\common\model\Classes::whereIn('id', $class_ids)->column('id,name');

        $this->success('', $list);
    }

    public function getClassNameByIds()
    {
        $class_ids = $this->request->request('class_ids/a');
        $list = \app\common\model\Classes::whereIn('id', $class_ids)->column('id,name');

        $this->success('', $list);
    }

    /**
     * 课程表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function course()
    {
        $class_id = $this->request->request('class_id');

        $classes = \app\common\model\Classes::get($class_id);

        if (!$classes) {
            $this->error('班级不存在');
        }

        //教师任课
        $teaches = Teach::alias('teach')
            ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id')
            ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('teach.school_id', $classes->school_id)
            ->where('FIND_IN_SET(:class_id,teach.class_ids)', ['class_id' => $class_id])
            ->column('teach.id,subject.name subject_name,user.nickname teacher_name', 'teach.id');

        // 课表
        $course_details = [];
        $list = CourseDetail::where('class_id', $class_id)->select();
        foreach ($list as $key => $value) {
            if (isset($teaches[$value['teach_id']])) {
                $value['subject_name'] = $teaches[$value['teach_id']]['subject_name'];
                $value['teacher_name'] = $teaches[$value['teach_id']]['teacher_name'];
                $course_details[$value['number']][$value['day']] = $value;
            }
        }

        //所有课节
        $class_days = [];
        $list = ClassDay::where('school_id', $classes->school_id)
            ->select();
        foreach ($list as $key => $class_day) {
            $class_days[$class_day['number']]['number'] = $class_day['number'];
            $class_days[$class_day['number']]['start_time'] = $class_day['start_time'];
            $class_days[$class_day['number']]['end_time'] = $class_day['end_time'];
            if (isset($course_details[$class_day['number']]) && isset($course_details[$class_day['number']][$class_day['day']])) {
                $temp_data = $course_details[$class_day['number']][$class_day['day']];
                $class_days[$class_day['number']]['data'][] = [
                    'subject_name' => $temp_data['subject_name'],
                    'teacher_name' => $temp_data['teacher_name'],
                ];
            } else {
                $class_days[$class_day['number']]['data'][] = [];
            }
            /*if (isset($course_details[$class_day['number']]) && isset($course_details[$class_day['number']][$class_day['day']])) {
                $class_days[$class_day['number']][] = $course_details[$class_day['number']][$class_day['day']];
            } else {
                $class_days[$class_day['number']][] = [];
            }*/
        }

        $this->success('', array_values($class_days));
    }

    /**
     * 班级今日课表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function todayCourse()
    {
        $class_id = $this->request->request('class_id');

        $classes = \app\common\model\Classes::get($class_id);

        if (!$classes) {
            $this->error('班级不存在');
        }

        $weekday = date('w', time());

        // 课表
        $course_details = [];
        $list = CourseDetail::where('class_id', $class_id)->where('day', $weekday)->select();
        $teach_ids = array_unique(array_column($list, 'teach_id'));
        //教师任课
        $teaches = Teach::alias('teach')
            ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id')
            ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('teach.school_id', $classes->school_id)
            ->whereIn('teach.id', $teach_ids)
            ->column('teach.id,subject.name subject_name,user.nickname teacher_name', 'teach.id');
        foreach ($list as $key => $value) {
            if (isset($teaches[$value['teach_id']])) {
                $value['subject_name'] = $teaches[$value['teach_id']]['subject_name'];
                $value['teacher_name'] = $teaches[$value['teach_id']]['teacher_name'];
                $course_details[$value['number']][$value['day']] = $value;
            }
        }

        //所有课节
        $class_days = [];
        $list = ClassDay::where('school_id', $classes->school_id)->where('day', $weekday)->select();
        foreach ($list as $key => $class_day) {
            $class_days[$class_day['number']]['number'] = $class_day['number'];
            $class_days[$class_day['number']]['start_time'] = $class_day['start_time_text'];
            $class_days[$class_day['number']]['end_time'] = $class_day['end_time_text'];
            $class_days[$class_day['number']]['start_stamp'] = date('Hi', strtotime($class_day['start_time'])) * 1;
            $class_days[$class_day['number']]['end_stamp'] = date('Hi', strtotime($class_day['end_time'])) * 1;
            if (isset($course_details[$class_day['number']]) && isset($course_details[$class_day['number']][$class_day['day']])) {
                $temp_data = $course_details[$class_day['number']][$class_day['day']];
                $class_days[$class_day['number']]['subject_name'] = $temp_data['subject_name'];
                $class_days[$class_day['number']]['teacher_name'] = $temp_data['teacher_name'];
            } else {
                $class_days[$class_day['number']]['subject_name'] = '';
                $class_days[$class_day['number']]['teacher_name'] = '';
            }
        }

        $this->success('', array_values($class_days));

    }

    /**
     * 根据班级ids获取班级位置
     */
    public function location()
    {
        $class_ids = $this->request->request('ids/a');

        if (!is_array($class_ids)) {
            $this->error('参数有误');
        }

        $list = \app\common\model\Classes::alias('classes')
            ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
            ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
            ->whereIn('classes.id', $class_ids)
            ->column('classes.id,classes.name,classroom.name classroom_name,building.name building_name', 'classes.id');

        $this->success('', $list);
    }

    /**
     * 班级人脸 教师、学生
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function faces()
    {
        $class_id = $this->request->request('id');
        $classes = \app\common\model\Classes::get($class_id);
        if (!$classes) {
            $this->error('班级不存在');
        }
        $data['teachers'] = \app\common\model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('teacher.school_id', $classes->school_id)
            ->field('teacher.id,user.nickname teacher_name,user.avatar,user.mobile,teacher.school_id')
            ->select();
        foreach ($data['teachers'] as $key => $student) {
            if (strpos($student->avatar, '/uploads') > -1) {
                $student->avatar = config('app_url') . $student->avatar;
            }
            $student->school_id = $classes->school_id;
        }

        $data['students'] = \app\common\model\ClassStudent::alias('a')
            ->join('__STUDENT__ b', 'b.id = a.student_id')
            ->where('a.class_id', $class_id)
            ->field('b.id,b.number,b.name,b.avatar,b.class_id')
            ->select();
        foreach ($data['students'] as $key => $student) {
            if (!strstr($student->avatar, 'http') && !strpos($student->avatar, 'https')) {
                if (strpos($student->avatar, '/uploads') > -1) {
                    $student->avatar = config('app_url') . $student->avatar;
                }
            }
            $student->school_id = $classes->school_id;
        }

        $this->success('', $data);
    }

    /**
     * 班级学生信息
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function students()
    {
        $class_id = $this->request->request('id');
        $list = \app\common\model\ClassStudent::alias('a')
            ->join('__STUDENT__ b', 'b.id = a.student_id')
            ->where('a.class_id', $class_id)
            ->field('b.id,b.number,b.name,b.avatar,b.school_id,b.grade_id,b.class_id')
            ->select();
        foreach ($list as $key => $student) {
            if (!strstr($student->avatar, 'http') && !strpos($student->avatar, 'https')) {
                if (strpos($student->avatar, '/uploads') > -1) {
                    $student->avatar = config('app_url') . $student->avatar;
                }
            }
        }
        $this->success('', $list);
    }

    /**
     * 班级任课教师信息
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function teachers()
    {
        $class_id = $this->request->request('id');
        $list = \app\common\model\Teach::alias('teach')
            ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id')
            ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('FIND_IN_SET(:class_id,teach.class_ids)', ['class_id' => $class_id])
            ->field('teacher.id,user.nickname teacher_name,user.avatar,user.mobile')
            ->group('teacher.id')
            ->select();
        foreach ($list as $key => $student) {
            if (!strstr($student->avatar, 'http') && strstr($student->avatar, '/uploads')) {
                $student->avatar = config('app_url') . $student->avatar;
            }
        }
        $this->success('', $list);
    }

    /**
     * 根据班级id获取全校教师
     */
    public function schoolTeachers()
    {
        $class_id = $this->request->request('id', 0);

        $classes = \app\common\model\Classes::get($class_id);
        if (!$classes) {
            $this->error('班级不存在');
        }

        $list = \app\common\model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->field('teacher.id,user.nickname name,user.gender,user.avatar')
            ->where('teacher.school_id', $classes->school_id)
            ->select();

        foreach ($list as $key => $value) {
            if (!strstr($value->avatar, 'http') && strstr($value->avatar, '/uploads')) {
                $value->avatar = config('app_url') . $value->avatar;
            }
            $value->school_id = $classes->school_id;
        }

        $this->success('', $list);
    }

    /**
     * 获取当前时间的课程考勤
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function currentCourseAttendance()
    {
        $class_id = $this->request->request('id', 0);

        $classes = \app\common\model\Classes::alias('classes')
            ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
            ->field('classes.*,grade.name grade_name')
            ->where('classes.id', $class_id)
            ->find();
        if (!$classes) {
            $this->error('班级不存在');
        }

        $current_time = date('H:i:s', time());
        $current_day = date('w', time());

        $result = CourseDetail::alias('a')
            ->join('__CLASS_DAY__ class_day', 'class_day.number = a.number and class_day.day = a.day and class_day.school_id = ' . $classes->school_id)
            ->join('__TEACH__ teach', 'teach.id = a.teach_id')
            ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id')
            ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->where('a.class_id', $class_id)
            ->where('a.day', $current_day)
            ->where('class_day.start_time', '<=', $current_time)
            ->where('class_day.end_time', '>=', $current_time)
            ->field('a.id,a.number,a.day,a.class_id,teach.is_clock_in,teach.clock_in_time,teach.school_id,subject.name subject_name,class_day.start_time,class_day.end_time,user.nickname teacher_name')
            ->find();

        if ($result) {
            $new_date = strtotime($result['start_time'] . " +{$result['clock_in_time']} minutes");

            if ($new_date < time()) {
                $this->success('', [
                    'id' => $result['id'],
                    'is_clock' => 0,
                    'start_time' => $result['start_time'],
                    'end_time' => $result['end_time'],
                    'att_range' => $result['clock_in_time'],
                    'att_name' => $result['subject_name'],
                    'type' => 3,
                    'school_id' => $result['school_id'],
                    'class_id' => $result['class_id'],
                    'grade_name' => $classes['grade_name'],
                    'class_name' => $classes['name'],
                    'teacher_name' => $result['teacher_name'],
                ]);
            }

            $this->success('', [
                'id' => $result['id'],
                'is_clock' => 1,
                'start_time' => $result['start_time'],
                'end_time' => $result['end_time'],
                'att_range' => $result['clock_in_time'],
                'att_name' => $result['subject_name'],
                'type' => 3,
                'school_id' => $result['school_id'],
                'class_id' => $result['class_id'],
                'grade_name' => $classes['grade_name'],
                'class_name' => $classes['name'],
                'teacher_name' => $result['teacher_name'],
            ]);
        }

        $result = CourseDetail::alias('a')
            ->join('__CLASS_DAY__ class_day', 'class_day.number = a.number and class_day.day = a.day and class_day.school_id = ' . $classes->school_id)
            ->join('__TEACH__ teach', 'teach.id = a.teach_id')
            ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id')
            ->join('__TEACHER__ teacher', 'teacher.id = teach.teacher_id', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->where('a.class_id', $class_id)
            ->where('a.day', $current_day)
            ->where('class_day.start_time', '>=', $current_time)
            ->field('a.id,a.number,a.day,a.class_id,teach.is_clock_in,teach.clock_in_time,teach.school_id,subject.name subject_name,class_day.start_time,class_day.end_time,user.nickname teacher_name')
            ->find();

        if ($result) {
            $this->success('', [
                'id' => $result['id'],
                'is_clock' => 1,
                'start_time' => $result['start_time'],
                'end_time' => $result['end_time'],
                'att_range' => $result['clock_in_time'],
                'att_name' => $result['subject_name'],
                'type' => 3,
                'school_id' => $result['school_id'],
                'class_id' => $result['class_id'],
                'grade_name' => $classes['grade_name'],
                'class_name' => $classes['name'],
                'teacher_name' => $result['teacher_name'],
            ]);
        } else {
            $this->error('该班级当前时间没有课程');
        }
    }

}